package com.cloud.rou.im.client.msg;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public abstract class MessageQueueExecutor<T> implements Runnable {

    private BlockingQueue<T> queue;

    private final ExecutorService executor;



    /**
     * query
     */
    private Map<Long,T> cacheMap;

    public MessageQueueExecutor(BlockingQueue<T> queue) {
        this.queue = queue;
        this.cacheMap = new ConcurrentHashMap<>();
        this.executor = Executors.newFixedThreadPool(1, r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            thread.setName("com.cloud.rou.im.client.msg.MessageQueueExecutor");
            return thread;
        });

    }

    public void add(T t) {
        queue.offer(t);
        cacheMap.put(getId(t),t);
    }
    public void remove(T t) {
        queue.remove(t);
        cacheMap.remove(getId(t));
    }

    @Override
    public void run() {
        while (true) {
            try {
                T take = queue.take();
                execute(take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public abstract void execute(T t);

    public abstract Long getId(T t);

    public void start() {
        executor.execute(this);
    }

}

